package com.sky.loveshop.utils;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/9/11 22:28
 */
@Slf4j
public class SignUtils {

    public static String generateSignature(Map<String, Object> params, String appSecret) {
        // 1. 将所有业务参数key做升序排序
        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        // 2. 业务参数key和value拼接成新的字符串
        StringBuilder s1 = new StringBuilder();
        for (String key : sortedKeys) {
            s1.append(key).append(params.get(key));
        }

        // 3. 把以上拼接的结果继续拼接应用密钥
        String s2 = s1 + appSecret;

        // 4. 对以上字符串进行md5加密
        String sign = SecureUtil.md5(s2);
        log.info("generateSignatureString unMd5=【{}】 md5=【{}】", s2, sign);
        return sign;
    }

    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    public static void main(String[] args) {
        final String APP_KEY = "app_key";
        final String APP_SECRET = "app_secret";

        Map<String, Object> params = new HashMap<>();
        params.put("app_key", APP_KEY);
        params.put("timestamp", 1652673840L);
        params.put("version", "1.0");
        params.put("deliver_status", 2);

        String signature = generateSignature(params, APP_SECRET);
        System.out.println("Signature: " + signature);
    }

}
